package com.ihome.android;

import java.util.Set;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;

import com.ihome.android.academy.AppMgrActivity;
import com.ihome.android.academy.DetailActivity;
import com.ihome.android.academy.MainActivity;
import com.ihome.android.netstatus.EANetWorkUtil.netType;
import com.ihome.android.util.AppUtils;
import com.ihome.android.util.log.LogUtil;

public abstract class EAActivity extends FragmentActivity {

	private final String		TAG							= EAActivity.class.getSimpleName();
	private static final int	DIALOG_ID_PROGRESS_DEFAULT	= 0x174980;

	private boolean				isRunning					= true;

	private BroadcastReceiver	mApplicationsReceiver		= null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		notifiyApplicationActivityCreating();
		onPreOnCreate(savedInstanceState);
		super.onCreate(savedInstanceState);
		getEAApp().getActivityMgr().push(this);
		initActivity();
		onAfterOnCreate(savedInstanceState);
		notifiyApplicationActivityCreated();
	}

	public EAApp getEAApp() {
		return (EAApp) getApplication();
	}

	private void notifiyApplicationActivityCreating() {
		getEAApp().onActivityCreating(this);
	}

	private void notifiyApplicationActivityCreated() {
		getEAApp().onActivityCreated(this);
	}

	protected void onPreOnCreate(Bundle savedInstanceState) {

	}

	private void initActivity() {
		LogUtil.d(EAActivity.this, "-->initActivity()");
		initInjector();

	}

	protected void onAfterOnCreate(Bundle savedInstanceState) {

	}

	/**
	 * 初始化注入器
	 */
	private void initInjector() {
		getEAApp().getInjector().injectResource(this);
		getEAApp().getInjector().inject(this);
	}

	@Override
	public void setContentView(int layoutResID) {

		super.setContentView(layoutResID);
		// 由于view必须在视图记载之后添加注入
		getEAApp().getInjector().injectView(this);
		onAfterSetContentView();
	}

	public void setContentView(View view, LayoutParams params) {
		super.setContentView(view, params);
		// 由于view必须在视图记载之后添加注入
		getEAApp().getInjector().injectView(this);
		onAfterSetContentView();
	}

	public void setContentView(View view) {
		super.setContentView(view);
		// 由于view必须在视图记载之后添加注入
		getEAApp().getInjector().injectView(this);
		onAfterSetContentView();
	}

	protected void onAfterSetContentView() {

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ID_PROGRESS_DEFAULT:
			ProgressDialog dlg = new ProgressDialog(this);
			// dlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			dlg.setMessage("正在加载...");
			dlg.setCancelable(true);
			return dlg;
		default:
			return super.onCreateDialog(id);
		}
	}

	/**
	 * 需要自定义进度条，请重写
	 */
	protected void showProgress() {
		showDialog(DIALOG_ID_PROGRESS_DEFAULT);
	}

	/**
	 * 隐藏进度条，需要重写的请重写
	 */
	protected void hideProgress() {
		try {
			removeDialog(DIALOG_ID_PROGRESS_DEFAULT);
		} catch (IllegalArgumentException iae) {

		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		isRunning = true;
		if (this instanceof AppMgrActivity || this instanceof MainActivity || this instanceof DetailActivity) {
			registerIntentReceivers();
		}
	}

	/**
	 * 网络连接连接时调用
	 */
	public void onConnect(netType type) {

	}

	/**
	 * 当前没有网络连接
	 */
	public void onDisConnect() {

	}

	@Override
	public void finish() {
		if (this instanceof AppMgrActivity || this instanceof MainActivity || this instanceof DetailActivity) {
			unregisterIntentReceivers();
		}

		int size = getEAApp().getActivityMgr().size();
		LogUtil.d(EAActivity.this, "Activity STACK size = " + size);
		for (int i = 0; i < size; i++) {
			Activity context = getEAApp().getActivityMgr().get(i);
			LogUtil.d(EAActivity.this, "Contains Activity = " + context.toString());
		}
		getEAApp().getActivityMgr().removeActivity(this);
		super.finish();
	}

	/**
	 * 退出应用程序
	 * 
	 * @param isBackground
	 *            是否开启后台运行,如果为true则为后台运行
	 */
	public void exitApp(Boolean isBackground) {
		getEAApp().exitApp(isBackground);
	}

	/**
	 * 退出应用程序
	 * 
	 */
	public void exitApp() {
		getEAApp().exitApp(false);
	}

	@Override
	protected void onPause() {
		super.onPause();
		isRunning = false;
	}

	public boolean getIsRunning() {
		return this.isRunning;
	}

	/**
	 * 退出应用程序，且在后台运行
	 * 
	 */
	public void exitAppToBackground() {
		getEAApp().exitApp(true);
	}

	private void unregisterIntentReceivers() {
		if (mApplicationsReceiver != null)
			unregisterReceiver(mApplicationsReceiver);
	}

	private void registerIntentReceivers() {
		if (mApplicationsReceiver == null)
			mApplicationsReceiver = new ApplicationsIntentReceiver();

		IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_MY_PACKAGE_REPLACED);
		filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
		filter.addDataScheme("package");
		registerReceiver(mApplicationsReceiver, filter);
	}

	/**
	 * Receives notifications when applications are added/removed
	 */
	private class ApplicationsIntentReceiver extends BroadcastReceiver {
		String pkgName = "";
		public void onReceive(Context context, Intent intent) {
			LogUtil.v(TAG, "ApplicationsIntentReceiver Aciton : " + intent.getAction());
			Bundle bundle = intent.getExtras();
			if (bundle != null) {
				Set<String> keySet = bundle.keySet();

				for (String key : keySet) {
					Object value = bundle.get(key);
					if (value instanceof String)
						LogUtil.v(TAG, "ApplicationsIntentReceiver key :" + key + "; value:" + (String) value);
					if (value instanceof Integer)
						LogUtil.v(TAG, "ApplicationsIntentReceiver key :" + key + "; value:" + (Integer) value);
					if (value instanceof Double)
						LogUtil.v(TAG, "ApplicationsIntentReceiver key :" + key + "; value:" + (Double) value);
					if (value instanceof Boolean)
						LogUtil.v(TAG, "ApplicationsIntentReceiver key :" + key + "; value:" + (Boolean) value);
				}

				// ApplicationsIntentReceiver key :android.intent.extra.UID; value:10042
				if (bundle.containsKey("android.intent.extra.UID")) {
					int uid = bundle.getInt("android.intent.extra.UID");
					pkgName = AppUtils.getPkgNameByUid(getApplicationContext(), uid);
				}
			}

			int size = getEAApp().getActivityMgr().size();
			if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED) || intent.getAction().equals(Intent.ACTION_MY_PACKAGE_REPLACED) || intent.getAction().equals(Intent.ACTION_PACKAGE_CHANGED)
					|| intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {

				for (int i = 0; i < size; i++) {
					final Context mcontext = getEAApp().getActivityMgr().get(i);

					if (mcontext instanceof AppMgrActivity) {
						((AppMgrActivity) mcontext).installationCheck(pkgName);
					}

					if (mcontext instanceof DetailActivity) {
						((DetailActivity) mcontext).installationCheck(pkgName);
					}
				}
			}
			else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED)) {
				for (int i = 0; i < size; i++) {
					final Context mcontext = getEAApp().getActivityMgr().get(i);

					LogUtil.v(TAG, "ACTION_PACKAGE_REMOVED mcontext :" + mcontext.toString());

					if (mcontext instanceof AppMgrActivity) {
						((AppMgrActivity) mcontext).uninstallationCheck();
					}

				}
			}

		}
	}
}
